package com.yungu.swift.system.sys.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.yungu.swift.assets.driver.model.dto.CarModelDto;
import com.yungu.swift.assets.driver.service.CarModelService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.mapper.IMapper;
import com.yungu.swift.base.model.PageVo;
import com.yungu.swift.base.service.impl.BaseServiceImpl;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.lbs.model.param.FenceParam;
import com.yungu.swift.lbs.model.vo.RegeoVo;
import com.yungu.swift.lbs.service.DistanceService;
import com.yungu.swift.lbs.service.FenceService;
import com.yungu.swift.lbs.service.LocationService;
import com.yungu.swift.system.sys.dao.*;
import com.yungu.swift.system.sys.model.dto.*;
import com.yungu.swift.system.sys.model.param.AdminRouteParam;
import com.yungu.swift.system.sys.model.param.AdminWayFenceParam;
import com.yungu.swift.system.sys.model.param.AdminWayPageParam;
import com.yungu.swift.system.sys.model.param.AdminWayParcelParam;
import com.yungu.swift.system.sys.model.vo.ScanCodeWayInfoVo;
import com.yungu.swift.system.sys.model.vo.SimpleWayInfo;
import com.yungu.swift.system.sys.model.vo.SysWayInfoVo;
import com.yungu.swift.system.sys.service.SysPointSiteService;
import com.yungu.swift.system.sys.service.SysWayService;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;


/**
 * SystemWayServiceImpl
 **/

@Slf4j
@Service
public class SysWayServiceImpl extends BaseServiceImpl<SysWayDto> implements SysWayService {

    @Autowired
    private SysWayMapper systemWayMapper;
    @Autowired
    private SysWayCalculationMapper systemWayCalculationMapper;
    @Autowired
    private SysPointSiteMapper systemPointSiteMapper;
    @Autowired
    private SysWayCompanyMapper systemWayCompanyMapper;
    @Autowired
    private SysWayFenceMapper sysWayFenceMapper;
    @Autowired
    private SysWayNightFareMapper sysWayNightFareMapper;

    @Reference
    private CarModelService carModelService;
    @Reference
    private LocationService locationService;
    @Reference
    private DistanceService distanceService;
    @Reference
    private FenceService fenceService;
    @Reference
    private SysPointSiteService sysPointSiteService;

    @Override
    protected IMapper<SysWayDto> getMapper() {
        return systemWayMapper;
    }

    /**
     * 返回所有线路起点+坐标默认起点（坐标处于起点范围，优先中心点距离最近）
     * //返回乘客当前坐标所在的城市的所有线路起点+坐标默认起点（坐标处于起点范围，优先中心点距离最近）
     * //若乘客坐标传空，则只返回所有城市起点，且不带默认匹配起点
     *
     * @param appid
     * @param pasLng
     * @param pasLat
     * @param onlyMatch
     * @return
     */
    @Override
    public ResponseData<List<SysPointSiteDto>> waysOriginByPoint(String appid, Double pasLng, Double pasLat, Integer onlyMatch, Integer busineeType, Integer orderDemand, Integer transferType) {
        //获取起点
        Map<String, Object> build = MapUtils.build();
        build.put("appid", appid);
        build.put("state", CommonConstant.STATE_NORMAL);
        //跨城拼车与跨城小件可单独开通业务
        if (busineeType != null && CommonConstant.BUSINESS_TYPE_PARCEL == busineeType) {
            build.put("parcelStatus", CommonConstant.STATUS_OPENED);
        } else {
            build.put("status", CommonConstant.STATUS_OPENED);
        }
        if (orderDemand != null) {
            build.put("wayType", orderDemand);
            //机场专线时 接机校验起点必须是固定点 送机起点必须是区域(临时逻辑)
            if (orderDemand.equals(CommonConstant.CROSSTOWN_ORDER_DEMADN_AIRPORT_SHUTTLE) && transferType != null && transferType == 1) {
                build.put("type", 2);
            } else if (orderDemand.equals(CommonConstant.CROSSTOWN_ORDER_DEMADN_AIRPORT_SHUTTLE) && transferType != null && transferType == 2) {
                build.put("type", 1);
            }
        }
        List<SysPointSiteDto> origins = systemPointSiteMapper.findOrigins(build);
        //默认匹配出发点，计算最优解
        if (onlyMatch != null && onlyMatch == 1 && CollectionUtils.isNotEmpty(origins)) {
            //获取（逆）地理位置编码
            String city = null;
            String district = null;
            if (null != pasLng && null != pasLat) {
                ResponseData<RegeoVo> pointJsonRS = locationService.regeo(pasLng, pasLat);
                if (pointJsonRS.isSuccess() && pointJsonRS.getData() != null) {
                    RegeoVo regeoVo = pointJsonRS.getData();
                    RegeoVo.AddressComponent addressComponent = regeoVo.getAddressComponent();
                    if (addressComponent != null) {
                        city = addressComponent.getCity();
                        district = addressComponent.getDistrict();
                    }
                }
            }
            SysPointSiteDto sysPointSiteDto = matchByOrigin(pasLng, pasLat, city, district, origins);
            if (sysPointSiteDto != null) {
                sysPointSiteDto.setMatchCurPoint(1);
                return ResponseData.buildSuccessResponse("匹配起点成功", Arrays.asList(sysPointSiteDto));
            } else {
                return ResponseData.buildSuccessResponse("请求起点接口成功", new ArrayList<>());
            }
        }
        return ResponseData.buildSuccessResponse("获取起点成功", origins);
    }

    /**
     * 冒泡排序选择距离最优解
     */
    private SysPointSiteDto matchByOrigin(Double lng, Double lat, String city, String district, List<SysPointSiteDto> origins) {
        // 默认取第一个，保证服务可用
        SysPointSiteDto tempPointSiteDto = null;
        double areaDistance = 0.0D;
        double siteDistance = 500D;
        for (SysPointSiteDto originPointSite : origins) {
            //匹配区域（按行政区域匹配：先匹配区县，如果全市则按照市级匹配）
            if (originPointSite.getType() == CommonConstant.POINT_SITE_TYPE_AREA) {
                if ((StringUtils.isNotEmpty(district) && (originPointSite.getIncludeAreas().contains(district) || district.equals(originPointSite.getCityName())))
                        || (StringUtils.isNotEmpty(city) && originPointSite.getIncludeAreas().equals("全部")
                        && originPointSite.getCityName().equals(city))) {
                    //目前：优先中心点距离最近
                    ResponseData<Double> distanceRS = distanceService.getDistance(lng, lat, originPointSite.getCenterLng(),
                            originPointSite.getCenterLat());
                    if (distanceRS.isSuccess() && (areaDistance == 0.0 || areaDistance > distanceRS.getData())) {
                        ResponseData checkRsd = sysPointSiteService.checkFence(lng, lat, originPointSite.getUuid());
                        if (checkRsd.isSuccess()) {
                            log.info("位置运营区域，{}", originPointSite.getName());
                            areaDistance = distanceRS.getData();
                            tempPointSiteDto = originPointSite;
                        } else {
                            log.info("位置点未进入运营区域，无法选中，{}", originPointSite.getName());
                        }
                    }
                }
            }
            //匹配固定点（距离中心点500米）
            if (originPointSite.getType() == CommonConstant.POINT_SITE_TYPE_POINT) {
                ResponseData<Double> distanceRS = distanceService.getDistance(lng, lat, originPointSite.getCenterLng(), originPointSite.getCenterLat());
                if (distanceRS.isSuccess() && distanceRS.getData() < siteDistance) {
                    siteDistance = distanceRS.getData();
                    tempPointSiteDto = originPointSite;
                }
            }
        }
        return tempPointSiteDto;
    }

    @Override
    public ResponseData<Map<String, Integer>> pointMatchedByAreaSiteCheck(Double pasLng, Double pasLat, String targetSiteUuid, String originSiteUuid) {
        //跨城小件存在历史地址 需要根据起点线路ID 判断终点位置与起点是否一致
        if (originSiteUuid != null) {
            Map<String, Object> paraMap = new HashMap<>();
            paraMap.put("originSiteUuid", originSiteUuid);
            paraMap.put("destSiteUuid", targetSiteUuid);
            paraMap.put("parcelStatus", CommonConstant.STATUS_OPENED);
            paraMap.put("state", CommonConstant.STATE_NORMAL);
            List<SysWayDto> wayList = systemWayMapper.findWithOriginDest(paraMap);
            if (wayList == null || wayList.size() == 0) {
                return ResponseData.buildErrorResponse(0, "终点与起点不在同一条线路，请重新选择地址");
            }
        }
        // 获取（逆）地理位置编码
        String city = null;
        String district = null;
        if (null != pasLng && null != pasLat) {
            ResponseData<RegeoVo> pointJsonRS = locationService.regeo(pasLng, pasLat);
            if (pointJsonRS.isSuccess() && pointJsonRS.getData() != null) {
                RegeoVo regeoVo = pointJsonRS.getData();
                RegeoVo.AddressComponent addressComponent = regeoVo.getAddressComponent();
                if (addressComponent != null) {
                    city = addressComponent.getCity();
                    district = addressComponent.getDistrict();
                }
            }
        }

        boolean isMatchOk = false;
        List<SysPointSiteDto> result = systemPointSiteMapper.list(MapUtils.build("uuid", targetSiteUuid));
        if (CollectionUtils.isNotEmpty(result)) {
            isMatchOk = matchByOrigin(pasLng, pasLat, city, district, result) != null;
        }
        Map<String, Integer> map = new HashMap<>(2);
        map.put("isMatchOk", isMatchOk ? 1 : 0);
        return ResponseData.buildSuccessResponse("校验成功", map);
    }

    @Override
    public ResponseData<List<SysPointSiteDto>> waysDestByOrigin(String appid, String originUuid, Integer orderDemand) {
        Map paras = MapUtils.build();
        paras.put("appid", appid);
        paras.put("originUuid", originUuid);
        paras.put("status", CommonConstant.STATUS_OPENED);
        paras.put("state", CommonConstant.STATE_NORMAL);
        if (orderDemand != null) {
            paras.put("wayType", orderDemand);
        }
        return ResponseData.buildSuccessResponse("获取线路匹配终点成功", systemPointSiteMapper.findDestByOrigin(paras));
    }

    @Override
    public ResponseData<List<SysWayDto>> findWithOriginDest(Map<String, Object> paramMap) {
        paramMap.put("state", CommonConstant.STATE_NORMAL);
        paramMap.put("status", CommonConstant.STATUS_OPENED);
        return ResponseData.buildSuccessResponse(systemWayMapper.findWithOriginDest(paramMap));
    }

    @Override
    public ResponseData<List<SysWayDto>> findWayInfoDetail(Map<String, Object> paramMap) {
        return ResponseData.buildSuccessResponse(systemWayMapper.findWithOriginDest(paramMap));
    }

    @Override
    public ResponseData<PageVo<SysWayDto>> findWithOriginDestByPage(AdminWayPageParam pageParam) {
        Map<String, Object> build = MapUtils.build(8);
        build.put("originCity", pageParam.getCityName());
        build.put("showCalculation", 1);
        build.put("showCar", 1);
        build.put("agentUuid", pageParam.getUserAgentUuid());
        build.put("adminAgentUuid", pageParam.getAdminAgentUuid());
        build.put("companyUuid", pageParam.getUserCompanyUuid());
        build.put("state", CommonConstant.STATE_NORMAL);
        build.put("status", pageParam.getStatus());
        PageBounds pageBounds = new PageBounds(pageParam.getPageNum(), pageParam.getPageSize());
        PageList<SysWayDto> pageList = systemWayMapper.findWithOriginDest(build, pageBounds);
        PageVo<SysWayDto> pageVo = new PageVo(pageParam.getPageNum(), pageParam.getPageSize(), pageList.getPaginator().getTotalCount());
        pageVo.setItems(pageList);
        return ResponseData.buildSuccessResponse(pageVo);
    }


    @Override
    @Transactional
    public ResponseData saveOrUpdate(AdminRouteParam routeParam) {
        //在高德新增成功的围栏集合
        List<String> addSuccessFenceList = new ArrayList<>();
        try {
            SysWayDto systemWayDto = new SysWayDto();
            BeanUtils.copyProperties(routeParam, systemWayDto);
            Map<String, Object> resultMap;
            //新增 注：线路往返 —— 即新增一条路线相当于增加两条线路
            if (StringUtils.isEmpty(routeParam.getUuid())) {
                systemWayDto.setCreateBy(routeParam.getUserUuid());
                //验证线路是否存在
                Map<String, Object> params = new HashMap(16);
                params.put("appid", systemWayDto.getAppid());
                params.put("originSiteUuid", systemWayDto.getOriginSiteUuid());
                params.put("destSiteUuid", systemWayDto.getDestSiteUuid());
                params.put("state", CommonConstant.STATE_NORMAL);
                int countExistedCur = systemWayMapper.count(params);
                params.clear();
                params.put("appid", systemWayDto.getAppid());
                params.put("originSiteUuid", systemWayDto.getDestSiteUuid());
                params.put("destSiteUuid", systemWayDto.getOriginSiteUuid());
                params.put("state", CommonConstant.STATE_NORMAL);
                int countExistedReturn = systemWayMapper.count(params);
                if (countExistedCur > 0 && countExistedReturn > 0) {
                    return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "已存在对应起终点路线");
                }
                //保存线路表
                systemWayDto.setUuid(StringUtils.buildUUID());
                systemWayDto.setState(CommonConstant.STATE_NORMAL);
                systemWayDto.setCreateOn(new Date());
                systemWayMapper.add(systemWayDto);
                //是否新增
                //保存价格
                resultMap = saveWayRelateInfo(systemWayDto, routeParam, true, true, addSuccessFenceList);

                //往返-返回路线
                SysWayDto wayReturn = new SysWayDto();
                BeanUtils.copyProperties(systemWayDto, wayReturn);
                wayReturn.setUuid(StringUtils.buildUUID());
                wayReturn.setOriginSiteUuid(systemWayDto.getDestSiteUuid());
                wayReturn.setDestSiteUuid(systemWayDto.getOriginSiteUuid());
                systemWayMapper.add(wayReturn);
                //保存价格
                saveWayRelateInfo(wayReturn, routeParam, true, false, addSuccessFenceList);
            } else {
                //更新线路表
                systemWayDto.setUpdateBy(routeParam.getUserUuid());
                systemWayMapper.edit(systemWayDto);
                //保存价格
                resultMap = saveWayRelateInfo(systemWayDto, routeParam, false, true, addSuccessFenceList);
            }
            resultMap.put("wayUuid", systemWayDto.getUuid());
            return ResponseData.buildSuccessResponse("操作成功，线路信息保存", resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            //存在异常时 删除已新增的围栏
            if (addSuccessFenceList.size() > 0) {
                for (String fenceGid : addSuccessFenceList) {
                    fenceService.deleteFence(fenceGid);
                }
            }
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "保存失败");
    }

    /**
     * 保存线路计价，围栏，夜间加价等相关信息
     *
     * @param wayDto
     * @param routeParam
     * @param isNew      是否新增
     */
    private Map<String, Object> saveWayRelateInfo(SysWayDto wayDto, AdminRouteParam routeParam, boolean isNew, boolean isPositive, List<String> addSuccessFenceList) {
        boolean isSuccess = true;
        StringBuilder msg = new StringBuilder();
        //取出需要操作的围栏
        List<AdminWayFenceParam> fenceParamList = routeParam.getWayFenceList();
        //非新增时 需要删除相关信息
        if (!isNew) {
            //删除旧的计价信息
            systemWayCalculationMapper.delByWay(wayDto.getUuid());
            //删除旧的围栏
            Map<String, Object> paraMap = new HashMap<>();
            paraMap.put("wayUuid", wayDto.getUuid());
            List<String> siteList = new ArrayList<>();
            siteList.add(wayDto.getOriginSiteUuid());
            siteList.add(wayDto.getDestSiteUuid());
            paraMap.put("siteList", siteList);

            List<SysWayFenceDto> wayFenceList = sysWayFenceMapper.list(paraMap);
            for (SysWayFenceDto sysWayFenceDto : wayFenceList) {
                //判断数据库取出的围栏是否在前端传回的集合中 若不存在 且起点经纬度一致的 则不作删除 直接更新围栏
                boolean isNeedDel = true;
                e:
                for (AdminWayFenceParam adminWayFenceParam : fenceParamList) {
                    if (StringUtils.equals(sysWayFenceDto.getFenceGid(), adminWayFenceParam.getFenceGid())) {
                        isNeedDel = false;
                        break e;
                    } else {
                        //围栏ID不相等时 判断经纬度是否一致 若一致 则判定为重复围栏 不作删除 并将存在的gid赋值给前端传回的参数对象中
                        String curCentreLngLat = sysWayFenceDto.getCentreLng() + "" + sysWayFenceDto.getCentreLat();
                        String paramCentreLngLat = adminWayFenceParam.getCentreLng() + "" + adminWayFenceParam.getCentreLat();
                        if ((sysWayFenceDto.getFenceType() == 0 && curCentreLngLat.equals(paramCentreLngLat))
                                || (sysWayFenceDto.getFenceType() == 1 && sysWayFenceDto.getPoints().equals(adminWayFenceParam.getPoints()))) {
                            adminWayFenceParam.setFenceGid(sysWayFenceDto.getFenceGid());
                            isNeedDel = false;
                            break e;
                        }
                    }
                }
                //若不需要删除 则进行下一条判断
                if (!isNeedDel) {
                    continue;
                }
                fenceService.deleteFence(sysWayFenceDto.getFenceGid());
            }
            sysWayFenceMapper.delByWayUuid(wayDto.getUuid());

            //删除旧的夜间加价
            sysWayNightFareMapper.delByWayUuid(wayDto.getUuid());
        }

        //保存计费信息
        List<AdminRouteParam.CalculationParam> calculationParams = routeParam.getCalculations();
        if (CollectionUtils.isNotEmpty(calculationParams)) {
            List<SysWayCalculationDto> calculationDtos = new ArrayList<>();
            for (AdminRouteParam.CalculationParam calculationParam : calculationParams) {
                SysWayCalculationDto calculationDto = new SysWayCalculationDto();
                calculationDto.setUuid(StringUtils.buildUUID());
                calculationDto.setWayUuid(wayDto.getUuid());
                calculationDto.setState(CommonConstant.STATE_NORMAL);
                calculationDto.setStatus(CommonConstant.STATUS_OPENED);
                calculationDto.setCarModelUuid(calculationParam.getCarModelUuid());
                calculationDto.setPriceUnit(calculationParam.getPriceUnit());
                calculationDto.setPriceWeep(calculationParam.getPriceWeep());
                calculationDto.setPriceTwoPerson(calculationParam.getPriceTwoPerson());
                calculationDtos.add(calculationDto);
            }
            //保存
            systemWayCalculationMapper.addBatch(calculationDtos);
        }

        //正向新增或者编辑时 保存围栏信息
        if (CollectionUtils.isNotEmpty(fenceParamList) && isPositive) {
            List<SysWayFenceDto> saveFenceList = new ArrayList<>();
            for (AdminWayFenceParam adminWayFenceParam : fenceParamList) {
                SysWayFenceDto sysWayFenceDto = new SysWayFenceDto();
                SysFenceDto sysFenceDto = new SysFenceDto();
                FenceParam fenceParam = new FenceParam();
                BeanUtils.copyProperties(adminWayFenceParam, sysFenceDto);
                BeanUtils.copyProperties(sysFenceDto, fenceParam);
                BeanUtils.copyProperties(sysFenceDto, sysWayFenceDto);
                sysWayFenceDto.setUuid(StringUtils.buildUUID());
                sysWayFenceDto.setWayUuid(wayDto.getUuid());
                sysWayFenceDto.setSiteUuid(adminWayFenceParam.getSiteUuid());
                sysWayFenceDto.setSiteType(adminWayFenceParam.getSiteType());
                sysWayFenceDto.setRaisePrice(adminWayFenceParam.getRaisePrice());
                sysWayFenceDto.setCreateOn(new Date());
                //围栏ID不为空时 作更新操作 为空时做新增操作
                if (StringUtils.isEmpty(adminWayFenceParam.getFenceGid())) {
                    ResponseData<String> responseData = fenceService.addFence(fenceParam);
                    if (!responseData.isSuccess() || StringUtils.isEmpty(responseData.getData())) {
                        log.info("围栏错误：{}", responseData.getMsg());
                        isSuccess = false;
                        msg.append("、").append(adminWayFenceParam.getFenceName());
                        continue;
                    }
                    sysWayFenceDto.setFenceGid(responseData.getData());
                    saveFenceList.add(sysWayFenceDto);
                    addSuccessFenceList.add(sysWayFenceDto.getFenceGid());
                } else {
                    ResponseData<Boolean> responseData = fenceService.updateFence(fenceParam);
                    if (!responseData.isSuccess()) {
                        log.info("围栏错误：{}", responseData.getMsg());
                        isSuccess = false;
                        msg.append("、").append(adminWayFenceParam.getFenceName());
                        continue;
                    }
                    saveFenceList.add(sysWayFenceDto);
                }
            }
            if (saveFenceList.size() > 0) {
                sysWayFenceMapper.addBatch(saveFenceList);
            }
        }

        //保存夜间加价信息
        List<AdminRouteParam.NightFareParam> nightFareList = routeParam.getNightFareList();
        if (CollectionUtils.isNotEmpty(nightFareList)) {
            List<SysWayNightFareDto> saveNightFareList = new ArrayList<>();
            for (AdminRouteParam.NightFareParam nightFareParam : nightFareList) {
                SysWayNightFareDto sysWayNightFareDto = new SysWayNightFareDto();
                BeanUtils.copyProperties(nightFareParam, sysWayNightFareDto);
                sysWayNightFareDto.setUuid(StringUtils.buildUUID());
                sysWayNightFareDto.setWayUuid(wayDto.getUuid());
                sysWayNightFareDto.setCreateOn(new Date());
                saveNightFareList.add(sysWayNightFareDto);
            }
            sysWayNightFareMapper.addBatch(saveNightFareList);
        }
        Map<String, Object> resultMap = new HashMap<>();
        //部分未成功
        if (!isSuccess) {
            resultMap.put("success", false);
            resultMap.put("msg", "围栏" + msg.substring(1) + "存在经纬度重复的情况，请重新编辑");
            return resultMap;
        }
        resultMap.put("success", true);
        return resultMap;
    }


    @Override
    public ResponseData<Boolean> updateStatus(String uuid, Integer status, Integer businessType) {
        boolean flag = false;
        if (CommonConstant.BUSINESS_TYPE_POOL == businessType) {
            flag = systemWayMapper.updateStatus(uuid, status) > 0;
        }
        if (CommonConstant.BUSINESS_TYPE_PARCEL == businessType) {
            flag = systemWayMapper.updateParcelStatus(uuid, status) > 0;
        }
        if (flag) {
            return ResponseData.buildSuccessResponse("操作成功，状态已修改", Boolean.TRUE);
        }
        return ResponseData.buildSuccessResponse("操作失败，数据未更新", Boolean.FALSE);
    }

    @Override
    public ResponseData<Boolean> updateState(String appid, String uuid, Integer state) {
        //校验底下开通业务
        Map<String, Object> paras = new HashMap(4);
        paras.put("appid", appid);
        paras.put("wayUuid", uuid);
        List<SysRegionalAgentDto> agents = systemWayCompanyMapper.getSubAgentByWay(paras);
        if (null != agents && !agents.isEmpty()) {
            StringBuffer msg = new StringBuffer("操作失败！当前线路已被分配于以下区域代理：<br>");
            for (SysRegionalAgentDto agent : agents) {
                msg.append(agent.getName() + "<br>");
            }
            msg.append(" 使用中");
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, msg.toString());
        }
        if (systemWayMapper.updateState(uuid, state) > 0) {
            //删除时  清空掉围栏
            if (state == -1) {
                List<SysWayFenceDto> wayFenceList = sysWayFenceMapper.list(MapUtils.build("wayUuid", uuid));
                for (SysWayFenceDto sysWayFenceDto : wayFenceList) {
                    fenceService.deleteFence(sysWayFenceDto.getFenceGid());
                }
            }
            return ResponseData.buildSuccessResponse("操作成功，状态已修改", Boolean.TRUE);
        }
        return ResponseData.buildSuccessResponse("操作失败，数据未更新", Boolean.FALSE);
    }


    @Override
    public ResponseData<Boolean> saveParcelRule(AdminWayParcelParam wayParcelParam) {

        //线路systemWay
        SysWayDto systemWayDto = new SysWayDto();
        systemWayDto.setUuid(wayParcelParam.getSystemWayUuid());
        systemWayDto.setParcelCancelRule(wayParcelParam.getParcelCancelRule());
        systemWayDto.setParcelManageRule(wayParcelParam.getParcelManageRule());
        systemWayDto.setParcelNumLimit(wayParcelParam.getParcelNumLimit());
        systemWayDto.setParcelStatus(wayParcelParam.getSaveType());
        systemWayMapper.edit(systemWayDto);

        //线路计价规则
        SysWayCalculationDto systemWayCalculationDto = new SysWayCalculationDto();
        systemWayCalculationDto.setParcelCancelFee(wayParcelParam.getParcelCancelFee());
        systemWayCalculationDto.setUuid(wayParcelParam.getSystemWayCalculationUuid());
        systemWayCalculationDto.setParcelPrice(wayParcelParam.getParcelPrice());

        //重新查询一次 防止同时编辑
        SysWayInfoVo systemWayInfoVo = systemWayMapper.getParcelRule(MapUtils.build("uuid", systemWayDto.getUuid()));
        if (systemWayInfoVo != null && systemWayInfoVo.getSystemWayCalculationUuid() == null) {
            //获取车型
            ResponseData<CarModelDto> carlevelRsd = carModelService.get(MapUtils.build("businessType", CommonConstant.BUSINESS_TYPE_PARCEL));
            if (carlevelRsd.isSuccess()) {
                CarModelDto carModelDto = carlevelRsd.getData();
                systemWayCalculationDto.setCarModelUuid(carModelDto.getUuid());
                systemWayCalculationDto.setUuid(StringUtils.buildUUID());
                systemWayCalculationDto.setStatus(CommonConstant.STATUS_OPENED);
                systemWayCalculationDto.setState(CommonConstant.STATE_NORMAL);
                systemWayCalculationDto.setWayUuid(systemWayDto.getUuid());
                systemWayCalculationMapper.add(systemWayCalculationDto);
            }
        }
        systemWayCalculationMapper.edit(systemWayCalculationDto);
        return ResponseData.buildSuccessResponse("保存成功", true);
    }

    @Override
    public ResponseData<SysWayInfoVo> getParcelRule(String uuid) {
        return ResponseData.buildSuccessResponse("跨城小件计价规则获取成功", systemWayMapper.getParcelRule(
                MapUtils.build("uuid", uuid)));
    }

    @Override
    public ResponseData<List<SimpleWayInfo>> fuzzyQueryByName(String wayName) {
        //起点线路名
        String originName = null;
        //终点线路名
        String destName = null;
        if (StringUtils.isNotEmpty(wayName)) {
            //解析有横杠的情况
            if (wayName.contains("-")) {
                String[] wayNameArr = wayName.split("-");
                switch (wayNameArr.length) {
                    case 1:
                        originName = wayNameArr[0].trim();
                        break;
                    case 2:
                        originName = wayNameArr[0].trim();
                        destName = wayNameArr[1].trim();
                        break;
                    default:
                        return ResponseData.buildSuccessResponse(null);
                }
            } else {
                originName = wayName.trim();
            }
        }
        Map<String, String> paramMap = new HashMap<>(4);
        paramMap.put("originName", originName);
        paramMap.put("destName", destName);
        return ResponseData.buildSuccessResponse(systemWayMapper.fuzzyQueryByName(paramMap));
    }

    /**
     * 获取扫码线路信息
     *
     * @param driverUuid
     * @return
     */
    @Override
    public ResponseData<List<ScanCodeWayInfoVo>> getScanCodeWayInfo(String driverUuid) {
        return ResponseData.buildSuccessResponse(systemWayMapper.getScanCodeWayInfo(driverUuid));
    }
}